package org.minproject.my_library_back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.minproject.my_library_back.common.CommonResponse;
import org.minproject.my_library_back.domain.Borrow;
import org.minproject.my_library_back.domain.Information;
import org.minproject.my_library_back.service.BorrowService;
import org.minproject.my_library_back.mapper.BorrowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author Lenovo
* @description 针对表【borrow】的数据库操作Service实现
* @createDate 2024-11-21 09:11:46
*/
@Service
public class BorrowServiceImpl extends ServiceImpl<BorrowMapper, Borrow>
    implements BorrowService{
    @Autowired
    private BorrowMapper borrowMapper;

    @Override
    public CommonResponse<List<Borrow>> getBorrows() throws Exception {
        List<Borrow> borrows = borrowMapper.selectList(null);
        return CommonResponse.createForSuccess("查询成功",borrows);
    }

    @Override
    public CommonResponse<List<Borrow>> getBorrowsByUserid(int userid) throws Exception {
        QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userid);
        List<Borrow> borrows = borrowMapper.selectList(queryWrapper);
        return CommonResponse.createForSuccess("查询成功",borrows);
    }

    @Override
    public CommonResponse<Borrow> addBorrow(Borrow borrow) throws Exception {
        borrowMapper.insert(borrow);
        return CommonResponse.createForSuccess("借阅成功",borrow);
    }

    @Override
    public CommonResponse<Borrow> deleteBorrow(Borrow borrow) throws Exception {
        borrowMapper.delete(new QueryWrapper<Borrow>().eq("user_id", borrow.getUserId()).eq("book_id", borrow.getBookId()));
        return CommonResponse.createForSuccess("删除成功",borrow);
    }

    @Override
    public CommonResponse<Borrow> returnBorrow(Borrow borrow) throws Exception {
        Borrow oldBorrow = borrowMapper.selectOne(new QueryWrapper<Borrow>().eq("user_id", borrow.getUserId()).eq("book_id", borrow.getBookId()));
        Date currentTime = new Date();
        borrowMapper.update(borrow, new QueryWrapper<Borrow>().eq("user_id", borrow.getUserId()).eq("book_id", borrow.getBookId()));
        borrow = borrowMapper.selectOne(new QueryWrapper<Borrow>().eq("user_id", borrow.getUserId()).eq("book_id", borrow.getBookId()));
        borrow.setBorrowTime2(currentTime);
        borrow.setBorrowTime1(oldBorrow.getBorrowTime1());
        borrowMapper.updateById(borrow);
        return CommonResponse.createForSuccess("归还成功",borrow);
    }
}




